package com.daffodil.storage.config;

import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import com.daffodil.storage.client.FastdfsStorageClient;
import com.daffodil.storage.client.FastdfsTrackerClient;
import com.daffodil.storage.properties.FastdfsProperties;
import com.daffodil.storage.properties.StorageProperties;
import com.github.tobato.fastdfs.domain.conn.Connection;
import com.github.tobato.fastdfs.domain.conn.FdfsConnectionPool;
import com.github.tobato.fastdfs.domain.conn.PooledConnectionFactory;
import com.github.tobato.fastdfs.domain.conn.TrackerConnectionManager;

/**
 * 
 * @author yweijian
 * @date 2023年10月31日
 * @version 1.0
 * @description
 */
@Component
@Configuration
@ConditionalOnProperty(name = StorageProperties.NAME, havingValue = StorageProperties.FASTDFS)
public class FastdfsClientConfig {

    @Bean
    @ConditionalOnMissingBean
    public PooledConnectionFactory pooledConnectionFactory(StorageProperties storageProperties) {
        FastdfsProperties properties = storageProperties.getFastdfs();
        PooledConnectionFactory factory = new PooledConnectionFactory();
        factory.setSoTimeout(properties.getSoTimeout());
        factory.setConnectTimeout(properties.getConnectTimeout());
        factory.setCharsetName(properties.getCharsetName());
        return factory;
    }

    @Bean
    @Primary
    @ConditionalOnMissingBean
    public FastdfsTrackerClient fastdfsTrackerClient(StorageProperties storageProperties, PooledConnectionFactory factory) {
        FastdfsProperties properties = storageProperties.getFastdfs();
        TrackerConnectionManager manager = new TrackerConnectionManager();
        GenericKeyedObjectPoolConfig<Connection> config = new GenericKeyedObjectPoolConfig<Connection>();
        FdfsConnectionPool pool = new FdfsConnectionPool(factory, config);
        manager.setPool(pool);
        manager.setTrackerList(properties.getTrackerList());
        manager.initTracker();
        return new FastdfsTrackerClient(manager);
    }

    @Bean
    @ConditionalOnMissingBean
    public FastdfsStorageClient fastdfsStorageClient(FastdfsTrackerClient trackerClient) {
        return new FastdfsStorageClient(trackerClient);
    }
}
